package com.share.thread;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @desc:
 * @author:caifan
 * @date:2021/2/28
 */
public class MutexLock {
    private Integer count = 0;
    private final Lock lock ;
    private final CountDownLatch countDownLatch;

    public MutexLock() {
        this.lock = new ReentrantLock();
        this.countDownLatch = new CountDownLatch(3);
    }

    private void count() {
        for (int i=0;i<1000;i++) {
            lock.lock();
            count += 1;
            lock.unlock();
        }
        countDownLatch.countDown();
    }

    public Integer call() throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        for (int i=0;i<3;i++) {
            executorService.execute(() -> {
                count();
            });
        }

        executorService.shutdown();
        countDownLatch.await();
        return count;
    }

    public static void main(String[] args) throws Exception {
        MutexLock mutexLock = new MutexLock();
        mutexLock.call();
        System.out.println(mutexLock.count);
        Thread.sleep(10 * 1000);
    }
}
